﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
using System.Windows;

namespace ASPItalia.ModelVirtualCasting.WPF.ViewModels
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class TaskbarViewModel : AsyncViewModel, ITaskService
    {
        private const string NAMED_PIPE_URI = "net.pipe://localhost/ModelVirtualCasting";

        private ServiceHost taskServiceHost;

        /// <summary>
        /// Start receiving remote tasks
        /// </summary>
        public void Listen()
        {
            // Create a service listening to remote tasks
            taskServiceHost = new ServiceHost(this);
            taskServiceHost.AddServiceEndpoint(typeof(ITaskService), new NetNamedPipeBinding(), NAMED_PIPE_URI);
            taskServiceHost.Open();
        }

        public void OpenWebSite(Uri site)
        {
            ITaskService service = GetTaskService();
            service.OpenWebSite(site);
        }

        public void ShowModel(int modelHash)
        {
            ITaskService service = GetTaskService();
            service.ShowModel(modelHash);
        }

        private static ITaskService GetTaskService()
        {
            ITaskService service = ChannelFactory<ITaskService>.CreateChannel(new NetNamedPipeBinding(), new EndpointAddress(NAMED_PIPE_URI));
            return service;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (taskServiceHost != null)
                taskServiceHost.Abort();

            taskServiceHost = null;
        }

        #region ITaskService Members

        void ITaskService.OpenWebSite(Uri site)
        {
            Process.Start(site.ToString());
        }

        void ITaskService.ShowModel(int modelHash)
        {
            // Look for Model using object hash code
            ModelViewModel mvm = ViewModelsContext.Current.MainViewModel.Candidates.FirstOrDefault(m => m.GetHashCode() == modelHash);
            if (mvm != null)
                ViewModelsContext.Current.MainViewModel.CurrentModel = mvm;
        }

        #endregion
    }

    [ServiceContract()]
    public interface ITaskService
    {
        [OperationContract()]
        void OpenWebSite(Uri site);

        [OperationContract()]
        void ShowModel(int modelHash);
    }
}
